import React, { useEffect, useMemo } from 'react'
import { useThemeStore } from '@/stores/themeStore'

export interface ModalProps {
  isOpen: boolean
  onClose: () => void
  title?: string
  children: React.ReactNode
  size?: 'sm' | 'md' | 'lg' | 'xl'
  showCloseButton?: boolean
  closable?: boolean
}

const Modal: React.FC<ModalProps> = ({
  isOpen,
  onClose,
  title,
  children,
  size = 'md',
  showCloseButton = true,
  closable = true
}) => {
  const themePreference = useThemeStore((state) => state.theme)
  const isDark = useMemo(() => {
    if (themePreference === 'dark') return true
    if (themePreference === 'light') return false
    return window.matchMedia('(prefers-color-scheme: dark)').matches
  }, [themePreference])

  // 处理 ESC 键关闭
  useEffect(() => {
    const handleEsc = (event: KeyboardEvent) => {
      if (event.key === 'Escape' && closable) {
        onClose()
      }
    }
    
    if (isOpen) {
      document.addEventListener('keydown', handleEsc)
      document.body.style.overflow = 'hidden'
    }
    
    return () => {
      document.removeEventListener('keydown', handleEsc)
      document.body.style.overflow = 'auto'
    }
  }, [isOpen, onClose, closable])

  if (!isOpen) return null

  const sizeClasses = {
    sm: 'max-w-md',
    md: 'max-w-lg',
    lg: 'max-w-2xl',
    xl: 'max-w-4xl'
  }

  const handleBackdropClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget && closable) {
      onClose()
    }
  }

  return (
    <div 
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      onClick={handleBackdropClick}
    >
      {/* 背景遮罩 */}
      <div className={`absolute inset-0 ${isDark ? 'bg-slate-950/60' : 'bg-slate-900/30'} backdrop-blur-sm transition-opacity`} />
      
      {/* 弹窗内容 */}
      <div
        className={`relative rounded-2xl shadow-2xl w-full ${sizeClasses[size]} max-h-[90vh] overflow-hidden transition-transform duration-200 backdrop-blur
        ${isDark
          ? 'bg-slate-900/90 border border-slate-700/70'
          : 'bg-white/95 border border-white/60'}`}
      >
        {/* 标题栏 */}
        {(title || showCloseButton) && (
          <div className={`flex items-center justify-between p-6 border-b ${isDark ? 'border-slate-700/60' : 'border-gray-200/70'}`}>
            <h3 className={`text-lg font-semibold ${isDark ? 'text-white' : 'text-gray-900'}`}>
              {title || ''}
            </h3>
            {showCloseButton && closable && (
              <button
                onClick={onClose}
                className={`${isDark ? 'text-slate-400 hover:text-slate-200' : 'text-gray-400 hover:text-gray-600'} transition-colors`}
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            )}
          </div>
        )}
        
        {/* 内容区域 */}
        <div className={`p-6 overflow-y-auto max-h-[calc(90vh-120px)] ${isDark ? 'text-slate-100 bg-slate-900/60' : 'text-gray-700 bg-white/60'}`}>
          {children}
        </div>
      </div>
    </div>
  )
}

export default Modal
